package server.alarmThreads;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import server.container.JPushInfo;
import server.container.LocalAlarm;
import server.container.SMSAlamierung;
import server.container.UserAlarm;

public class UnifiedAlarmThread extends Thread {
	
	/**
	 * 
	 */
	private static Logger logger = Logger.getLogger(UnifiedAlarmThread.class);
	
	private Semaphore userAlarmFuellstand;
	
	private ConcurrentLinkedQueue<UserAlarm> userAlarmList;
	
	private SMSVersaender smsVersaender = new SMSVersaender();
	
	private ProwlAlarmierer prowlAlarmierer = new ProwlAlarmierer();
	
	private LocalAlarmierer localAlarmierer = new LocalAlarmierer();
	
	private NotifyMyAndroidAlarmierer notifyAlarmierer = new NotifyMyAndroidAlarmierer();
	
	public UnifiedAlarmThread(ConcurrentLinkedQueue<UserAlarm> userAlarmList,
			Semaphore userAlarmFuellstand) {
	
		this.userAlarmFuellstand = userAlarmFuellstand;
		this.userAlarmList = userAlarmList;
	}
	
	@Override
	public void run() {
	
		while (true) {
			try {
				userAlarmFuellstand.tryAcquire(5000, TimeUnit.MILLISECONDS);
				UserAlarm alarm = userAlarmList.poll();
				if (alarm != null) {
					if (alarm instanceof SMSAlamierung) {
						smsVersaender.sendSMS((SMSAlamierung) alarm);
					} else if (alarm instanceof LocalAlarm) {
						localAlarmierer.alarmiere((LocalAlarm) alarm);
					} else if (alarm instanceof JPushInfo) {
						JPushInfo pushAlarm = (JPushInfo) alarm;
						if (pushAlarm.getPushInfoTyp() == JPushInfo.PROWL) {
							prowlAlarmierer.alarmiere(pushAlarm);
						}
						if (pushAlarm.getPushInfoTyp() == JPushInfo.NOTIFYMYANDROID) {
							notifyAlarmierer.alarmiere(pushAlarm);
						}
					}
				}
			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}
}
